package com.carl.mall.controller;


import com.alibaba.fastjson.JSON;
import com.carl.common.constant.AuthConstant;
import com.carl.common.constant.SMSConstant;
import com.carl.common.exception.BizCodeEnum;
import com.carl.common.utils.R;
import com.carl.common.vo.MemberVO;
import com.carl.mall.feign.MemberFeignService;
import com.carl.mall.feign.ThirdPartFeignService;
import com.carl.mall.vo.UserLoginVO;
import com.carl.mall.vo.UserRegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;



@Controller
@Slf4j
public class LoginController {


    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private ThirdPartFeignService partFeignService;

    @Autowired
    private MemberFeignService memberFeignService;


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone") String phone){
        //防止60秒重复发送
        Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + phone);
        if (redisCode !=null){
//            String co = JSONObject.toJSONString(redisCode);
           String co = redisCode.toString();
            if (!"".equals(co)){
               long l =  Long.parseLong(redisCode.toString().split("_")[1]);
               if (System.currentTimeMillis() - l <= 60000){
                   return R.error(BizCodeEnum.VALID_SMS_EXCEPTION.getCode(),BizCodeEnum.VALID_SMS_EXCEPTION.getMsg());
               }
            }
        }
        // 生成随机的验证码
//        String code = UUID.randomUUID().toString().substring(0, 5);
        //
        Random random = new Random();
        int randomNumber = random.nextInt(90000) + 10000;
        String code = String.valueOf(randomNumber);
        partFeignService.sendCode(phone,code);
        code = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PERFIX + phone,code,10, TimeUnit.MINUTES);
        return R.ok();

    }

    /**
     * 注册接口
     * @param registerVO
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVO registerVO, BindingResult result, Model model){
        HashMap<String, String> map = new HashMap<>();
        if (result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field   = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            model.addAttribute("error",map);
            return "/reg";
        }
        //参数合法
        //取验证码 先从redis中取到code
        String code = (String) redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + registerVO.getPhone());
        if (code != null && !"".equals(code)){
            code = code.split("_")[0];
            if (!code.equalsIgnoreCase(registerVO.getCode())){
                map.put("code","验证码有误请重新获取验证码");
                model.addAttribute("error",map);
                return "/reg";
            }
            else {
                redisTemplate.delete(SMSConstant.SMS_CODE_PERFIX + registerVO.getPhone());
                System.out.println("验证码正确");
                R register = memberFeignService.register(registerVO);
                if (register.getCode() == 0) {
                    //注册成功
                    return "redirect:http://carl.auth.com/login.html";
                }else {
                     // 注册失败
                    map.put("msg",register.getCode()+":"+register.get("msg"));
                    model.addAttribute("error",map);
                    return "/reg";
                }

            }
        }

        return "/reg";

    }


    /**
     * 登录接口
     *
     */
    @PostMapping("/login")
    public String login(UserLoginVO userLoginVO, RedirectAttributes  redirectAttributes, HttpSession session){
        R r = memberFeignService.login(userLoginVO);
        if (r.getCode() == 0){
            //表示登录成功
            String entityJson = (String) r.get("entity");
            MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            return "redirect:http://mall.carl.com/home";
        }
        log.error("登陆异常：密码或用户名错误 ->>>>>>>>>>>>>>>>>>>>>>>" + (String) r.get("msg"));
        session.setAttribute("errors",r.get("msg"));
        // 表示登录失败,重新跳转到登录页面
        return "redirect:http://auth.carl.com/login.html";
    }



}
